package lol.niconico.libtest.ui.paging

import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.observe
import androidx.paging.LoadState
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import dagger.hilt.EntryPoint
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import lol.niconico.libtest.R
import lol.niconico.libtest.ui.paging.adapter.FooterAdapter
import lol.niconico.libtest.ui.paging.adapter.GitHubAdapter

@AndroidEntryPoint
class PagingFragment : Fragment() {

    companion object {
        fun newInstance() = PagingFragment()
    }

    private val viewModel by viewModels<PagingViewModel>()

    private val recyclerView: RecyclerView by lazy {
        requireView().findViewById<RecyclerView>(R.id.recyclerView).apply {
            adapter = mGitHubAdapter
        }
    }

    private val mGitHubAdapter: GitHubAdapter by lazy {
        GitHubAdapter().apply {
            withLoadStateFooter(FooterAdapter(this))
        }
    }

    private val mSwipeRefreshLayout: SwipeRefreshLayout by lazy {
        requireView().findViewById<SwipeRefreshLayout>(R.id.swipe_refresh_layout).apply {
            setOnRefreshListener {
                mGitHubAdapter.refresh()
                mSwipeRefreshLayout.isRefreshing = false
            }
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        return inflater.inflate(R.layout.main_fragment, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        recyclerView
        mSwipeRefreshLayout

        viewModel.pageDataLiveData.observe(viewLifecycleOwner) {
            mGitHubAdapter.submitData(lifecycle, it)
        }

        lifecycleScope.launchWhenStarted {
            mGitHubAdapter.loadStateFlow.collectLatest { state ->
                mSwipeRefreshLayout.isRefreshing = state.refresh is LoadState.Loading
            }
        }
    }
}